import IconApp from '@/components/icon/IconApp';
import IconBiliBili from '@/components/icon/IconBiliBili';
import IconDouyin from '@/components/icon/IconDouyin';
import IconKuaishou from '@/components/icon/IconKuaishou';
import IconToutiao from '@/components/icon/IconToutiao';
import IconWeb from '@/components/icon/IconWeb';
import IconWeChatChannels from '@/components/icon/IconWeChatChannels';
import IconWeChatOfficialAccount from '@/components/icon/IconWeChatOfficialAccount';
import IconWeibo from '@/components/icon/IconWeibo';
import {
  deletedRecord,
  selectRecord,
  updateRecordExamine,
  updateRecordState,
} from '@/services/api/api-assess-week-emphasize-record';
import { CheckCircleTwoTone, CloseCircleTwoTone, InfoCircleTwoTone } from '@ant-design/icons';
import { ActionType, ModalForm, ProList } from '@ant-design/pro-components';
import { DrawerForm } from '@ant-design/pro-form';
import {
  Alert,
  Button,
  Col,
  Descriptions,
  Divider,
  Flex,
  Image,
  message,
  QRCode,
  Row,
  Space,
  Spin,
  Tag,
  Typography,
  Upload,
  UploadFile,
} from 'antd';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import React, { useEffect, useRef, useState } from 'react';
import { useAccess } from 'umi';
import AddExhibitionRecord from '../exhibition/AddExhibitionRecord';
import EditRecord from './EditRecord';
interface DetailRecordProps {
  entrance: 'vote' | 'rank' | 'record' | 'exhibition';
  id: string;
  name?: string;
  exhibitionId?: string;
  trigger?: JSX.Element;
  onRefurbish: () => void;
  onExhibitionRefurbish: () => void;
}

const DetailRecord: React.FC<DetailRecordProps> = ({
  entrance,
  id,
  name,
  exhibitionId,
  trigger,
  onRefurbish,
  onExhibitionRefurbish,
}) => {
  const access = useAccess();

  const [details, setDetailsState] = useState<AssessWeekEmphasizeRecordData.SelectRecord>();

  /**
   * 预览使用
   */
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewData, setPreviewData] = useState<{
    id: string;
    name: string;
    mimeType: string;
    url?: string;
  }>();
  const [previewOnlineUrl, setPreviewOnlineUrl] = useState<string>();
  const [previewLoading, setPreviewLoading] = useState(true);

  /**
   * 窗口开关
   */
  const [drawerFormVisible, setDrawerFormVisible] = useState(false);

  const getWindowSize = () => ({
    innerHeight: window.innerHeight,
    innerWidth: window.innerWidth,
  });
  const [windowSize, setWindowSize] = useState(getWindowSize());
  const handleResize = () => {
    setWindowSize(getWindowSize());
  };
  useEffect(() => {
    // 监听
    window.addEventListener('resize', handleResize);
    // 销毁
    return () => window.removeEventListener('resize', handleResize);
  });

  const iframeRef = useRef(null);

  const handleLoad = () => {
    console.log('加载完成');
    setPreviewLoading(false);
  };

  useEffect(() => {
    const iframe = iframeRef.current;
    iframe?.addEventListener('load', handleLoad);
    return () => {
      iframe?.removeEventListener('load', handleLoad);
    };
  }, [previewOnlineUrl]);

  /**
   * 获取 详情
   * @param key
   */
  const loadDetails = async () => {
    try {
      const response = await selectRecord({ id });
      if (response.code === 0) {
        setDetailsState(response.data);
      }
    } catch (error) { }
  };

  const actionRef = useRef<ActionType>();

  const reportTypeView = () => {
    let color = '';
    let label = '';

    if (details?.dataReportType == 1) {
      color = 'orange';
      label = '好报道';
    } else if (details?.dataReportType == 2) {
      color = 'blue';
      label = '好评论';
    } else if (details?.dataReportType == 3) {
      color = 'cyan';
      label = '好创意报道';
    }

    return <Tag color={color}>{label}</Tag>;
  };

  function splitUrls(input: string): string[] {
    const regex = /https:\/\/[^\s,;]+|https:\/\/.*?(?=https:\/\/|$)/g;
    const matches: string[] = [];
    let match: RegExpExecArray | null;

    while ((match = regex.exec(input)) !== null) {
      matches.push(match[0]);
      // 避免零长度匹配导致无限循环
      if (match.index === regex.lastIndex) regex.lastIndex++;
    }

    return matches;
  }

  return (
    <DrawerForm
      key="details_details_drawer_form"
      title={
        <Space>
          <span>{details?.isExhibition == 1 ? <Tag color="orange">三好作品</Tag> : '详情'}</span>
        </Space>
      }
      drawerProps={{
        // maskClosable: false,
        destroyOnClose: true,
        width: 600,
      }}
      trigger={
        trigger ? (
          trigger
        ) : (
          <a
            target="_blank"
            style={{
              textAlign: 'start',
            }}
          >
            {name}
          </a>
        )
      }
      open={drawerFormVisible}
      onOpenChange={(visible) => {
        if (visible) {
          loadDetails();
        } else {
          onRefurbish();
        }
        setDrawerFormVisible(visible);
      }}
      submitter={
        entrance != 'vote' &&
        details?.isExamine == 1 &&
        details?.isExhibition == 0 &&
        (access.传播质效x配置x管理员
          ? {
            submitButtonProps: {
              style: {
                display: 'none',
              },
            },
            render: (props, defaultDoms) => {
              return [
                ...defaultDoms,
                <AddExhibitionRecord
                  id={exhibitionId ? exhibitionId : details?.exhibitionId}
                  recordData={details}
                  onRefurbish={() => { }}
                  onSave={() => {
                    onExhibitionRefurbish();
                  }}
                />,
                <ModalForm
                  trigger={
                    <Button type="primary" danger>
                      下架
                    </Button>
                  }
                  key={'modal_form_release_state_discard'}
                  title={
                    <>
                      <CheckCircleTwoTone
                        style={{
                          marginRight: 8,
                        }}
                        twoToneColor="#ff4d4f"
                      />
                      是否确认下架该稿件
                    </>
                  }
                  autoFocusFirstInput
                  modalProps={{
                    width: 400,
                    destroyOnClose: true,
                    onCancel: () => console.log('run'),
                  }}
                  submitter={{
                    submitButtonProps: {
                      type: 'primary',
                      style: { background: '#ff4d4f' },
                    },
                  }}
                  onFinish={async (values) => {
                    props.submit();
                    return true;
                  }}
                />,
              ];
            },
          }
          : details?.isLock == 1
            ? false
            : {
              submitButtonProps: {
                style: {
                  display: 'none',
                },
              },
              render: (props, defaultDoms) => {
                return [
                  ...defaultDoms,
                  <EditRecord
                    id={id}
                    onRefurbish={function (): void {
                      loadDetails();
                    }}
                  />,
                  <ModalForm
                    trigger={
                      <Button
                        type="primary"
                        style={{
                          background: details?.state == 1 ? '#faad14' : '',
                        }}
                      >
                        {details?.state == 1 ? '主动下架' : '主动上架'}
                      </Button>
                    }
                    key={'modal_form_release_state_discard'}
                    title={
                      <>
                        <InfoCircleTwoTone
                          style={{
                            marginRight: 8,
                          }}
                          twoToneColor={details?.state == 1 ? '#faad14' : ''}
                        />
                        {details?.state == 1 ? '是否确认下架该稿件' : '是否确认上架该稿件'}
                      </>
                    }
                    autoFocusFirstInput
                    modalProps={{
                      width: 400,
                      destroyOnClose: true,
                      onCancel: () => console.log('run'),
                    }}
                    submitter={{
                      submitButtonProps: {
                        type: 'primary',
                        style: { background: details?.state == 1 ? '#faad14' : '' },
                      },
                    }}
                    onFinish={async (values) => {
                      props.submit();
                      return true;
                    }}
                  />,
                  <ModalForm
                    trigger={
                      <Button type="primary" danger>
                        删除
                      </Button>
                    }
                    key={'modal_form_release_state_discard'}
                    title={
                      <>
                        <CloseCircleTwoTone
                          style={{
                            marginRight: 8,
                          }}
                          twoToneColor="#ff4d4f"
                        />
                        确认删除
                      </>
                    }
                    autoFocusFirstInput
                    modalProps={{
                      width: 400,
                      destroyOnClose: true,
                    }}
                    submitter={{
                      submitButtonProps: {
                        type: 'primary',
                        style: { background: details?.state == 1 ? '#ff4d4f' : '' },
                      },
                    }}
                    onFinish={async (values) => {
                      console.log('==删除=');

                      const response = await deletedRecord({
                        id: id,
                      });

                      if (response.code == 0) {
                        message.success('删除成功');
                        setDrawerFormVisible(false);
                        onRefurbish();
                        return true;
                      } else {
                        return false;
                      }
                    }}
                  />,
                ];
              },
            })
      }
      onFinish={async (values) => {
        if (access.传播质效x配置x管理员) {
          const response = await updateRecordExamine({
            id: details?.id,
            isExamine: 0,
          });

          if (response.code === 0) {
            message.success('下架成功');
            onRefurbish();
            return true;
          } else {
            return false;
          }
        } else if (access.传播质效x配置x运营员) {
          const response = await updateRecordState({
            id: details?.id,
            state: details?.state == 1 ? 0 : 1,
          });

          if (response.code === 0) {
            message.success(details?.state == 1 ? '下架成功' : '上架成功');
            onRefurbish();
            return true;
          } else {
            return false;
          }
        }
      }}
    >
      <Spin
        style={{
          textAlign: 'center',
        }}
        spinning={details === undefined}
      >
        {details !== undefined && (
          <>
            <Descriptions column={1}>
              <Descriptions.Item label="媒体类型">{details?.datahubLevelName}</Descriptions.Item>
              <Descriptions.Item label="所属区域">{details?.areaName}</Descriptions.Item>
              <Descriptions.Item label="主管单位">
                {details?.appointSourceOrganizationNames?.map((item) => (
                  <Tag>{item}</Tag>
                ))}
              </Descriptions.Item>
            </Descriptions>

            <Descriptions>
              <Descriptions.Item label="报道类型">{reportTypeView()}</Descriptions.Item>
            </Descriptions>
            <Descriptions>
              <Descriptions.Item label="发布日期">
                {dayjs(details?.dataReleaseTime).format('YYYY-MM-DD')}
              </Descriptions.Item>
              <Descriptions.Item label="报送日期">
                {dayjs(details?.createdTime).format('YYYY-MM-DD')}
              </Descriptions.Item>
            </Descriptions>
            <Divider
              orientation="left"
              style={{
                fontSize: 14,
                fontWeight: 'bold',
              }}
            >
              稿件信息
            </Divider>
            <Typography.Title
              level={4}
              copyable={{
                text: async () =>
                  new Promise((resolve) => {
                    resolve(details.dataName);
                  }),
              }}
              style={{
                marginBottom: '20px',
              }}
            >
              <a>{details?.dataName}</a>
            </Typography.Title>
            {details?.authors?.length > 0 && (
              <Descriptions column={4}>
                <Descriptions.Item label="作者">
                  <Space size={[0, 8]} wrap>
                    {details?.authors?.map((item) => {
                      return <Tag key={item}>{item}</Tag>;
                    })}
                  </Space>
                </Descriptions.Item>
              </Descriptions>
            )}
            {details?.reason && (
              <>
                <Descriptions column={4}>
                  <Descriptions.Item label="推荐理由"> </Descriptions.Item>
                </Descriptions>
                <Typography.Paragraph style={{ marginTop: '-20px' }}>
                  <blockquote>{details?.reason}</blockquote>
                </Typography.Paragraph>
              </>
            )}
            <Divider
              orientation="left"
              style={{
                fontSize: 14,
                fontWeight: 'bold',
              }}
            >
              互动数据
            </Divider>
            <Descriptions column={4}>
              <Descriptions.Item label="阅读量/播放量">
                {details?.dataReadCount + details?.dataPlayCount}
              </Descriptions.Item>
            </Descriptions>
            <Descriptions column={4}>
              {/* <Descriptions.Item label="阅读量">
                {details?.datahubChannelNames?.includes('微信公众号') ||
                details?.datahubChannelNames?.includes('微博') ||
                details?.datahubChannelNames?.includes('今日头条')
                  ? details?.dataReadCount
                  : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="播放量">
                {details?.datahubChannelNames?.includes('抖音') ||
                details?.datahubChannelNames?.includes('微信视频号')
                  ? details?.dataPlayCount
                  : '-'}
              </Descriptions.Item> */}
              <Descriptions.Item label="点赞量">{details?.dataLikeCount}</Descriptions.Item>
              <Descriptions.Item label="转发量">{details?.dataCollectCount}</Descriptions.Item>
            </Descriptions>
            <Divider
              orientation="left"
              style={{
                fontSize: 14,
                fontWeight: 'bold',
              }}
            >
              发布数据
            </Divider>
            <ProList<AssessWeekEmphasizeRecordData.ProveSo>
              toolBarRender={false}
              rowKey="id"
              showActions="hover"
              grid={{ gutter: 16, column: 1 }}
              headerTitle={false}
              dataSource={details?.proves}
              itemCardProps={{
                bodyStyle: {
                  paddingTop: 0,
                  paddingLeft: 12,
                  paddingRight: 12,
                  paddingBottom: 12,
                },
              }}
              metas={{
                title: {
                  render: (
                    dom: React.ReactNode,
                    entity: AssessWeekEmphasizeRecordData.ProveSo,
                    index: number,
                    action,
                  ) => {
                    let icon;
                    if (entity.datahubChannelName == '微信公众号') {
                      icon = <IconWeChatOfficialAccount width={15} height={15} />;
                    } else if (entity.datahubChannelName == '微信视频号') {
                      icon = <IconWeChatChannels width={15} height={15} />;
                    } else if (entity.datahubChannelName == '微博') {
                      icon = <IconWeibo width={15} height={15} />;
                    } else if (entity.datahubChannelName == '抖音') {
                      icon = <IconDouyin width={15} height={15} />;
                    } else if (entity.datahubChannelName == '今日头条') {
                      icon = <IconToutiao width={15} height={15} />;
                    } else if (entity.datahubChannelName == '快手') {
                      icon = <IconKuaishou width={15} height={15} />;
                    } else if (entity.datahubChannelName == '哔哩哔哩') {
                      icon = <IconBiliBili width={15} height={15} />;
                    } else if (entity.datahubChannelName == '客户端') {
                      icon = <IconApp width={15} height={15} />;
                    } else if (entity.datahubChannelName == '网站') {
                      icon = <IconWeb width={15} height={15} />;
                    }
                    return (
                      <Space align={'center'}>
                        <Tag color={entity.appointSourceType == 1 ? 'gold' : 'green'}>
                          {entity.appointSourceType == 1 ? '官方' : '轻骑兵'}
                        </Tag>
                        <Flex justify={'center'} align={'center'}>
                          {icon}
                          <span
                            style={{
                              // marginTop: 2,
                              marginLeft: 5,
                            }}
                          >
                            {entity.datahubSourceName}
                          </span>
                        </Flex>
                      </Space>
                    );
                  },
                },
                actions: {
                  render: (
                    dom: React.ReactNode,
                    entity: AssessWeekEmphasizeRecordData.ProveSo,
                    index: number,
                    action,
                  ) => {
                    return (
                      <>
                        {entity.datahubChannelName == '微信视频号' && entity.dataUrl && (
                          <span
                            style={{
                              fontSize: '14px',
                              color: '#00000073',
                            }}
                          >
                            注：该视频号链接只在微信移动端可用

                          </span>
                        )}
                      </>
                    );
                  },
                },
                content: {
                  render: (
                    dom: React.ReactNode,
                    entity: AssessWeekEmphasizeRecordData.ProveSo,
                    index: number,
                    action,
                  ) => {
                    return (
                      <div>
                        <Descriptions
                        // column={4}
                        >
                          {entity.datahubChannelName == '微信公众号' ||
                            entity.datahubChannelName == '微博' ||
                            entity.datahubChannelName == '今日头条' ||
                            entity.datahubChannelName == '客户端' ||
                            entity.datahubChannelName == '网站' ? (
                            <Descriptions.Item label="阅读量">
                              {entity?.dataReadCount}
                            </Descriptions.Item>
                          ) : (
                            <Descriptions.Item label="播放量">
                              {entity?.dataPlayCount}
                            </Descriptions.Item>
                          )}

                          <Descriptions.Item label="点赞量">
                            {entity?.dataLikeCount}
                          </Descriptions.Item>
                          <Descriptions.Item label="转发量">
                            {entity?.dataCollectCount}
                          </Descriptions.Item>
                        </Descriptions>

                        {entity.datahubChannelName == '微信视频号' &&
                          false &&
                          entity?.dataVideoUrl && (
                            <ModalForm<{
                              name: string;
                              company: string;
                            }>
                              title="观看视频"
                              trigger={<a target={'_blank'}>观看视频</a>}
                              autoFocusFirstInput
                              width="700px"
                              modalProps={{
                                destroyOnClose: true,
                              }}
                              submitter={false}
                            >
                              <Flex justify={'center'} align={'center'}>
                                <video
                                  style={{
                                    width: '690px',
                                    height: '980px',
                                  }}
                                  controls
                                  src={entity.dataVideoUrl}
                                />
                              </Flex>
                            </ModalForm>
                          )}
                        {entity.dataUrl && (
                          <>
                            <Row>
                              <Col span={entity.datahubChannelName == '微信视频号' ? 12 : 24}><Typography.Paragraph
                                style={{}}
                                copyable={{
                                  text: async () =>
                                    new Promise((resolve) => {
                                      resolve(entity.dataUrl);
                                    }),
                                }}
                              >
                                <blockquote>
                                  {splitUrls(entity.dataUrl).map((item) => (
                                    <>
                                      <a target={'_blank'} href={item}>
                                        {item}
                                      </a>
                                      <br></br>
                                    </>
                                  ))}
                                </blockquote>
                              </Typography.Paragraph>

                              </Col>
                              {entity.datahubChannelName == '微信视频号' && <Col span={12}>
                                <Flex justify={'center'} align={'center'}>
                                  <QRCode
                                    errorLevel="H"
                                    value={entity.dataUrl}
                                    icon={"https://xtbs.ljsyy.net/resources/xtbs-assess-logo-shipinhao.png"}
                                  />
                                </Flex>
                              </Col>}
                            </Row>
                          </>
                        )}

                        <Upload
                          listType="picture-card"
                          fileList={entity?.attachments?.map((item) => {
                            return {
                              uid: item.id,
                              name: item.name,
                              url: item.content,
                              mimeType: item.mimeType,
                              status: 'done',
                            };
                          })}
                          showUploadList={{
                            showRemoveIcon: false,
                          }}
                          onPreview={async (file: UploadFile) => {
                            if (!file.url && !file.preview) {
                            }
                            setPreviewData({
                              id: file?.uid,
                              name: file?.name,
                              mimeType: file?.mimeType,
                              url: file?.url,
                            });
                            setPreviewOpen(true);
                          }}
                        />
                        {entity.remarks && (
                          <Typography.Paragraph style={{}}>
                            <blockquote>{entity.remarks}</blockquote>
                          </Typography.Paragraph>
                        )}
                      </div>
                    );
                  },
                },
              }}
            />
            <DrawerForm
              title={previewData?.name}
              drawerProps={{
                width: 900,
                destroyOnClose: true,
              }}
              open={previewOpen}
              onOpenChange={async (visible) => {
                if (visible) {
                  if (
                    previewData?.mimeType !== null &&
                    previewData?.mimeType?.indexOf('image') > -1
                  ) {
                    //图片预览
                  } else {
                    setPreviewLoading(true);

                    //   const response = await cuesAttachmentPreview({
                    //     id: previewData?.id,
                    //   });

                    //   if (response.code === 0) {
                    //     setPreviewOnlineUrl(response.data);
                    //   } else {
                    //     message.error('暂时无法预览');
                    //     setPreviewLoading(false);
                    //   }
                  }
                } else {
                  setPreviewOpen(false);
                  setPreviewData(undefined);
                  setPreviewOnlineUrl(undefined);
                }
              }}
              submitter={{
                searchConfig: {
                  submitText: '下载',
                },
              }}
              onFinish={async (values) => {
                window.open(previewData?.url, '_blank');
              }}
            >
              <Alert
                style={{
                  marginBottom: 20,
                }}
                message="部分文件系统可能暂不支持在线预览，建议下载到本地"
                type="warning"
                showIcon
              />
              {previewData?.mimeType !== null && previewData?.mimeType?.indexOf('image') > -1 ? (
                <Image width="100%" src={previewData?.url} />
              ) : (
                <Spin spinning={previewLoading}>
                  <iframe
                    ref={iframeRef}
                    src={previewOnlineUrl}
                    height={windowSize.innerHeight - 220}
                    width="100%"
                    frameBorder="0"
                    // scrolling="false"
                    allowFullScreen={true}
                  // scrolling={'no'}
                  />
                </Spin>
              )}
            </DrawerForm>
          </>
        )}
      </Spin>
    </DrawerForm>
  );
};

export default DetailRecord;
